<template>
  <view class="chat-container">
    <scroll-view
      class="chat-content"
      :style="{ height: state.scrollViewHeight + 'px' }"
      :scroll-y="true"
      :scroll-top="state.scrollTop"
      :scroll-with-animation="true"
    >
      <!-- 聊天消息列表 -->
      <view class="scroll-view-content">
        <view
          class="message-item"
          v-for="(message, index) in chatList"
          :key="index"
          :class="{
            'message-left': message.sender === 'me',
            'message-right': message.sender !== 'me',
          }"
        >
          <view class="message-avatar">
            <!-- <image :src="message.sender === 'me' ? state.avatarMe : state.avatarThem" /> -->
            <!-- <image :src="message.sender == 'me' ? message.createAvatar : message.userAvatar" /> -->
            <image :src="message.createAvatar" />
            <!-- <image :src="message.userAvatar" v-else /> -->
          </view>
          <view
            class="message-text-wrapper"
            :class="message.sender === 'me' ? 'me' : 'them'"
            v-if="message.type == 0"
          >
            <text
              class="message-text"
              :style="{
                'text-align': message.sender === 'me' ? 'right' : 'left',
              }"
              >{{ message.content }}</text
            >
            <!-- <text class="message-time">{{ message.time }}</text> -->
          </view>
          <view class="chat-img" v-if="message.type == 1">
            <image :src="message.content" mode="widthFix" />
          </view>

          <view class="chat-img" v-if="message.type == 2">
            <video
              class="video"
              :src="message.content"
              controls
              show-center-play-btn
              play-btn-position="center"
            ></video>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 				-->
    <!-- <view class="chat-input">
            <input type="text" :focus="state.focus" v-model="state.newMessage" @focus="scrollToBottom"
                @confirm="sendMessage" class="ipt" placeholder="输入消息..." />
        </view> -->

    <view class="chat-input">
      <TextareaComment
        @send="sendMessage"
        ref="textareaCommentRef"
        v-model:showInputPop="showInputPop"
        @closeInputPop="closeInputPop"
        @sendImage="sendImage"
        @sendVideo="sendVideo"
      >
      </TextareaComment>
    </view>
  </view>
</template>

<script setup>
import { reactive, onMounted, nextTick, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import TextareaComment from "@/components/comment/textareaComment.vue";
import { deleteObjectEmptyKey } from "@/utils/util";
import { postChat, chatPage, getUserInfo } from "@/api/apiList";

const userInfo = ref({});
const user = async () => {
  const res = await getUserInfo(); // showNum > 1 不用付钱
  if (res.code == 200) {
    userInfo.value = res.data;
  }
};

// 评论输入框组件
const textareaCommentRef = ref();
// 新建评论弹窗
const showInputPop = ref(true);
// 关闭输入框
const closeInputPop = () => {
  showInputPop.value = false;
};

const state = reactive({
  messages: [], // 初始为空数组
  newMessage: "", // 用户输入的消息
  scrollViewHeight: 0,
  scrollTop: 0,
  focus: true,
});

const uqeryID = ref();
const userId = ref("");
onLoad(async (option) => {
  uni.setNavigationBarTitle({
    title: option.name,
  });
  query.value.userId = option.id;
  userId.value = option.id;
  await user();
  getChatPage();
});

// 获取聊天记录
const query = ref({
  userId: uqeryID.value,
});
const chatList = ref([]);
const getChatPage = async () => {
  const meUserId = userInfo.value.userId;
  console.log(meUserId, "meUserId");
  const res = await chatPage(query.value);
  if (res.code == 200) {
    chatList.value = res.data.map((item) => {
      return {
        sender: meUserId == item.createUser ? "me" : "them",
        content: item.content,
        userAvatar: item.userAvatar,
        userName: item.userName,
        type: item.type,
        createAvatar: item.createAvatar,
        avatar:
          meUserId == item.createUser ? item.createAvatar : item.userAvatar,
      };
    });
    console.log(chatList.value, "chatList.value");
  }
};

// 发送消息
const formData = ref({
  userId: "",
  type: "0",
  content: "",
});
async function sendMessage(data) {
  console.log(data);
  formData.value.content = data.content;
  formData.value.type = 0;
  formData.value.userId = userId.value;
  const newFormData = deleteObjectEmptyKey(formData.value);
  const res = await postChat(newFormData);
  if (res.code == 200) {
    getChatPage();
    scrollToBottom();
  }
}

const sendImage = async (data) => {
  if (data.length) {
    formData.value.content = data[0];
    formData.value.type = 1;
    formData.value.userId = userId.value;
    const newFormData = deleteObjectEmptyKey(formData.value);
    const res = await postChat(newFormData);
    if (res.code == 200) {
      getChatPage();
      scrollToBottom();
    }
  }
};

const sendVideo = async (data) => {
  if (data.length) {
    formData.value.content = data;
    formData.value.type = 2;
    formData.value.userId = userId.value;
    const newFormData = deleteObjectEmptyKey(formData.value);
    const res = await postChat(newFormData);
    if (res.code == 200) {
      getChatPage();
      scrollToBottom();
    }
  }
};

// 获取当前时间
function getFormattedTime() {
  // 你可以根据自己的需求格式化时间
  return new Date().toLocaleTimeString();
}

// 滚动页面到底部
function scrollToBottom() {
  state.scrollTop = 0;
  // 滚动到聊天内容的底部
  nextTick(() => {
    let view = uni.createSelectorQuery().select(".scroll-view-content");
    view
      .boundingClientRect((res) => {
        let top = res.height - state.scrollViewHeight;
        if (top > 0) {
          state.scrollTop = top;
          console.log(state.scrollTop, "state.scrollTop");
        }
      })
      .exec();
  });
}

onMounted(async () => {
  getClineHeight();
});

const getClineHeight = () => {
  uni.getSystemInfo({
    success: (res) => {
      state.scrollViewHeight =
        res.windowHeight - uni.upx2px(80) - getBarHeight();
      console.log(state.scrollViewHeight, "state.scrollViewHeight");
      scrollToBottom();
    },
  });
};

const getBarHeight = () => {
  const res = uni.getSystemInfoSync();
  if (res.platform === "ios") {
    return 44 + res.statusBarHeight;
  } else if (res.platform === "android") {
    return 48 + res.statusBarHeight;
  } else {
    return 0;
  }
};
</script>
<style lang="scss" scoped>
.me {
  background-color: #fff !important;
  color: #000 !important;
}

.them {
  background-color: #0753fd !important;
  color: #fff !important;
}

.video {
  border-radius: 20rpx;
}

.chat-img {
  // flex: 1;
  display: flex;
  flex-direction: column;
  border-radius: 8rpx;
  padding: 31rpx 23rpx;
  margin-left: 30rpx;
  /* For right messages */
  margin-right: 30rpx;

  image {
    width: 500rpx;
  }
}

.chat-input {
  width: 100%;
  // height: 170rpx;
  // background: #ffffff;
  // padding: 0 30rpx 176rpx 30rpx;

  // .ipt {
  //     background: #f6f6f6;
  //     border-radius: 8rpx;
  //     width: 690rpx;
  //     height: 80rpx;
  //     padding-left: 20rpx;
  // }
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 10rpx;
  box-sizing: border-box;
  // height: 1266rpx;
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10rpx;
}

.message-left {
  flex-direction: row-reverse;
  text-align: right;
}

.message-avatar {
}

image {
  width: 82rpx;
  height: 82rpx;
  border-radius: 8rpx;
}

.message-left .message-avatar {
  margin-right: 0;
  /* Override for left messages */
}

.message-text-wrapper {
  // flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 8rpx;
  padding: 31rpx 23rpx;
  margin-left: 30rpx;
  /* For right messages */
  margin-right: 30rpx;
  /* For left messages */
  max-width: 40%;
}

.message-left .message-text-wrapper {
  margin-left: 0;
  /* Override for left messages */
}

.message-text {
  word-wrap: break-word;
}

.message-left .message-text {
}

.message-time {
  font-size: 12rpx;
  color: #999;
  margin-top: 5rpx;
}

.scroll-view-content {
  padding-bottom: 88rpx;
  padding-top: 20rpx;
}
/* Rest of the styles... */
</style>
